<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use fast\Tree;
use think\Cache;

/**
 * 分组管理
 *
 * @icon fa fa-circle-o
 */
class Cate extends Backend
{

    /**
     * Cate模型对象
     * @var \app\admin\model\Cate
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Cate;

        // 使用缓存优化树形结构数据
        $cacheKey = 'cate_tree_data';
        $groupdata = Cache::get($cacheKey);
        
        if (!$groupdata) {
            // 使用模型优化方法获取数据
            $list = $this->model->getTreeData();

            // 将数据给到这个方法中
            Tree::instance()->init($list);
            $groupdata = [];
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            
            // 遍历 $result 数组，将每个树节点的 name 字段作为 $groupdata 数组中一个条目的值，将 id 字段作为键。
            $groupdata[0] = '顶级栏目';
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
            
            // 缓存5分钟
            Cache::set($cacheKey, $groupdata, 300);
        }

        $this->view->assign("statusList", $groupdata);
        $this->view->assign("statusList1", [
            0 => '正常',
            1 => '隐藏'
        ]);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        //判断请求为Ajax
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            // 优化查询，只获取必要字段，减少数据传输
            $list = $this->model
                ->field('id,pid,name,sort,updatetime,createtime,status,sub_name')
                ->where($where)
                ->order(['sort' => 'asc', 'id' => 'asc'])
                ->paginate(200); // 减少分页数量，提高响应速度
            
            // 优化数据可见性设置
            $list->each(function ($row) {
                $row->visible(['id', 'sort', 'name', 'updatetime', 'createtime', 'status', 'sub_name']);
            });

            // 使用缓存优化树形结构处理
            // 使用简单的缓存键，避免序列化问题
            $cacheKey = 'cate_tree_list_' . md5($this->request->get('page', 1) . $this->request->get('limit', 50));
            $result1 = Cache::get($cacheKey);
            
            if (!$result1) {
                //初始化并传入结果
                Tree::instance()->init($list);
                //获取树形结构列表
                $result1 = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
                // 缓存2分钟
                Cache::set($cacheKey, $result1, 120);
            }
            
            //返回值
            $result = array("total" => $list->total(), "rows" => $result1);
            //返回
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 清除缓存
     */
    public function clearCache()
    {
        $this->model->clearCache();
        Cache::rm('cate_tree_data');
        Cache::rm('cate_tree_list_*');
        $this->success('缓存清除成功');
    }

    /**
     * 性能监控
     */
    public function performance()
    {
        $startTime = microtime(true);
        
        // 测试查询性能
        $list = $this->model->getTreeData();
        $queryTime = microtime(true) - $startTime;
        
        // 测试树形结构处理性能
        $treeStartTime = microtime(true);
        Tree::instance()->init($list);
        $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        $treeTime = microtime(true) - $treeStartTime;
        
        $data = [
            'total_records' => count($list),
            'query_time' => round($queryTime * 1000, 2) . 'ms',
            'tree_process_time' => round($treeTime * 1000, 2) . 'ms',
            'total_time' => round((microtime(true) - $startTime) * 1000, 2) . 'ms',
            'memory_usage' => round(memory_get_usage(true) / 1024 / 1024, 2) . 'MB',
            'peak_memory' => round(memory_get_peak_usage(true) / 1024 / 1024, 2) . 'MB'
        ];
        
        return json($data);
    }

    /**
     * 批量操作优化
     */
    public function batch()
    {
        if ($this->request->isPost()) {
            $ids = $this->request->post('ids');
            $action = $this->request->post('action');
            
            if (!$ids || !$action) {
                $this->error('参数错误');
            }
            
            $ids = is_array($ids) ? $ids : explode(',', $ids);
            
            switch ($action) {
                case 'delete':
                    $result = $this->model->where('id', 'in', $ids)->delete();
                    break;
                case 'enable':
                    $result = $this->model->where('id', 'in', $ids)->update(['status' => 0]);
                    break;
                case 'disable':
                    $result = $this->model->where('id', 'in', $ids)->update(['status' => 1]);
                    break;
                default:
                    $this->error('不支持的操作');
            }
            
            if ($result !== false) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        }
        
        return $this->view->fetch();
    }
}
